package com.haoziqi.chapter_07;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.windows.GlobalWindow;
import org.apache.flink.util.Collector;

/**
 * description
 * created by A on 2021/3/11
 */
public class Flink02_CountWindow {
    public static void main(String[] args) {
        //1.创建环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        SingleOutputStreamOperator<WaterSensor> sensorDS = env
                .socketTextStream("localhost", 9999)
                .map(new MapFunction<String, WaterSensor>() {
                    @Override
                    public WaterSensor map(String value) throws Exception {
                        // 切分
                        String[] line = value.split(",");
                        return new WaterSensor(line[0], Long.valueOf(line[1]), Integer.valueOf(line[2]));

                    }
                });
        // 分组之前开窗：所有的数据都会进入同一个并行实例
//        sensorDS.windowAll()

        KeyedStream<WaterSensor, String> sensorKS = sensorDS.keyBy(sensor -> sensor.getId());
        //sensorKS.countWindow(5); //基于计数的滚动窗口
        WindowedStream<WaterSensor, String, GlobalWindow> swensorWS = sensorKS.countWindow(5, 2);//基于计数的 滑动窗口
        swensorWS.process(
                new ProcessWindowFunction<WaterSensor,String, String, GlobalWindow>() {
                    @Override
                    public void process(String key, Context context, Iterable<WaterSensor> elements, Collector<String> out) throws Exception {
                        out.collect("key=" + key + "\n" +
                                "数据条数:" + elements.spliterator().estimateSize() + "\n\n"
                        );
                    }
                }
        ).print();


        //提交任务
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
